<?php

namespace app\web\controller;
use app\commons\model\ActivityVideo;
use app\commons\model\Member;
use app\commons\model\MemberSale;
use app\commons\model\SaleCard;
use app\commons\model\SaleVerifyer;
use app\commons\model\UserCard;
use app\commons\model\Sale;
use app\job\DouyinVideo;
use douyin\Dy;
use redis\Redis;
use think\Exception;
use think\exception\ValidateException;
use think\Db;
use collar\CollarBag;
use think\facade\Log;
use think\Queue;
use app\web\validate\Card as CardValidate;
use video\Alivideo;

class Cards
{
    /**
     * 获取用户卡券列表
     */
    public function index(UserCard $saleCard){
        $user_id = session('user');
        $page = request()->get('page') ?? 1;
        $data = $saleCard->where(['user_id'=>$user_id])->paginate(10,false,['query'=>request()->param()]);
        return jsonp($data);
    }

    /**
     * 获取优惠券详情
     */
    public function details(UserCard $saleCard){
        try {
            $user_id = session('user');
            $id = request()->get('id') ?: 1;
            $data = $saleCard->where(['user_id'=>$user_id,'id'=>$id])->find();
            if(!$data) throw new Exception('数据错误！');

            $data['merch'] = Sale::where(['id'=>$data['sale_id']])->field(['poi_address','real_share','poi_share'])->find();
            if(!empty($data['merch'])) $data['merch']['real_share'] = $data['merch']['poi_share'];
            $data['auth_url'] = request()->domain(true).'?id='.$id;
        }catch (Exception $exception){
            throw new ValidateException('服务器内部错误！');
        }
        return jsonp($data);
    }

    /**
     * 核销优惠券
     */
    public function writeCard(UserCard $userCard){
        try {
            $user_id = session('user');
            $id = request()->post('id') ?: 0;
            if(!$id) throw new Exception('参数错误！');
            $data = $userCard->where(['id'=>$id])->find();
            if(!$data) throw new Exception('非法操作！');
            $saleUser = SaleVerifyer::where(['member_id'=>$user_id,'sale_id'=>$data['sale_id']])->find();
            if(!$saleUser) throw new Exception('操作不合法，请用绑定账号扫码！');
            $updateData = [];
            if(strtotime($data['expire_time']) < time()){
                //优惠券状态不对
                $where[] = ['expire_time','<',date('Y-m-d H:i:s')];
                $where[] = ['status','=',0];
                $updateRes = UserCard::where(['id'=>$id])->update(['status'=>2]);
                if(!$updateRes){
                    throw new Exception('优惠券已过期！');
                }
                throw new Exception('优惠券已过期！');
            }
            //更新优惠券信息
            $UserCardRes = UserCard::where(['id'=>$id])->update(['status'=>1]);
            if(!$UserCardRes) throw new Exception('核销失败！');
            $data['status'] = 2;
            $data['status_text'] = '已使用';
            return jsonp($data);
        }catch (Exception $exception){
            throw new ValidateException($exception->getMessage());
        }
    }

    /**
     * 领取卡券
     */
    public function create(UserCard $saleCard, Sale $sale){
        $data = request()->param();
        $validate = new CardValidate();
        if (!$validate->check($data)) {
            throw new ValidateException($validate->getError());
        }
        $mac_info = session('mac_info');
        if(!$mac_info) return jsonp_error(422,'请重新扫码！');
        if(!Redis::redis()->get($mac_info->redis_name)) return jsonp_error(422,'请重新扫描设备上的二维码！');
        $data['mac_id'] = $mac_info->mac_id;
        //删除redis缓存(设备信息)
        Redis::redis()->delete($mac_info->redis_name);
        Db::startTrans();
        try {
            $info = $sale->where(['id'=>$data['sale_id']])->find();
            if(empty($info)) throw new Exception('参数错误！');
            if($info['status'] == 1) throw new Exception('活动已结束！');
            if($info['view'] >= $info['number'])  throw new Exception('扫码次数不足！');
            $videoInfo = ActivityVideo::where(['id'=>$data['activity_video_id'],'sale_id'=>$data['sale_id']])->field(['id','is_use'])->find();
            if(!$videoInfo) throw new Exception('视频错误啦！');
            if($videoInfo['is_use'] != 0) throw new Exception('视频参数错误！');
            $addData = [];
            if($info['paytype'] == 0){
                $crad = $info['card'];
                //判断卡券数量是否足够
//                if($crad['num'] <= $crad['receive_num']) throw new Exception('数量不足！');
                //获取用户已领取的数量
                $user_num = UserCard::where(['user_id'=>session('user'),'sale_id'=>$info['id']])->count('id');
                if($user_num >= $crad['user_limit']) throw new Exception('每人限领'.$crad['user_limit'].'张！');
//                if($crad['num'] <= $crad['receive_num']) throw new Exception('数量不足！');
                $expire_time = $crad['endtime'];
                $start_time = $crad['starttime'];
                if($crad['term'] > 0){
                    $expire_time = date('Y-m-d H:i:s',time() + (86400 * $crad['term']));
                    $start_time = date('Y-m-d H:i:s',time());
                }
                $addData = [
                    'user_id'=>session('user'),
                    'sale_id'=>$data['sale_id'],
                    'card_id'=>$info['card_id'],
                    'type'=>$crad['type'],
                    'code'=>create_order_sn(),
                    'price'=>$crad['price'],
                    'expire_time'=>$expire_time,
                    'start_time'=>$start_time,
                    'full_money'=>$crad['full_money'],
                    'activity_video_id'=>$data['activity_video_id'] ?? 1,
                ];
                $res = $saleCard->allowField(true)->save($addData);
                if(!$res) throw new Exception('添加优惠券失败！');
                $addData['id'] = $saleCard->id;
            }
            //获取用户零袋子次数和同步用户信息
            //finish_task_num 已经使用的次数
            //global_task_num 可使用的次数
            $userData = CollarBag::syncUser(session('user'),$data['mac_id']);
            Log::info('同步用户信息结果：');
            Log::info($userData);

            if(empty($userData)) throw new Exception('获取设备信息失败！');
            if(!isset($userData['finish_task_num'])) throw new Exception('获取取袋次数失败！');
            if($userData['finish_task_num'] >= $userData['global_task_num']) throw new Exception('领取失败，请明天再来！');
//            //出袋子操作，视频操作
            $chudaiRes = CollarBag::receive(session('user'),$data['mac_id']);
            if(!$chudaiRes) throw new Exception('出袋失败！');
            //更新领取优惠券数量
//            $cradRes = SaleCard::where(['id'=>$info['card_id']])->setInc('receive_num');
//            if(!$cradRes) throw new Exception('领取优惠券失败！');

            //更新视频使用
            $ActivityVideoRes = ActivityVideo::where(['id'=>$data['activity_video_id']])->update(['is_use'=>'1','use_time'=>date('Y-m-d H:i:s'),'user_id'=>session('user')]);
            if(!$ActivityVideoRes) throw new Exception('领取失败！');
            //更新用户参与记录
            if(!MemberSale::where(['sale_id'=>$data['sale_id'],'member_id'=>session('user')])->value('id')){
                $MemberSaleRes = MemberSale::create(['sale_id'=>$data['sale_id'],'member_id'=>session('user')]);
                if(!$MemberSaleRes) throw new Exception('领取失败！');
            }
            Db::commit();
            //发布视频操作
            $job = Queue::push(DouyinVideo::class,['user_id'=>session('user'),'sale_id'=>$data['sale_id'],'activity_video_id'=>$data['activity_video_id'] ?? 1]);
            $addData['job'] = $job;
            if(isset($addData['start_time'])) $addData['start_time'] = date('Y-m-d',strtotime($addData['start_time']));
            if(isset($addData['expire_time'])) $addData['expire_time'] = date('Y-m-d',strtotime($addData['expire_time']));
            return jsonp($addData);
        }catch (Exception $exception){
            Db::rollback();
            throw new ValidateException($exception->getMessage());
        }
    }

    /**
     * 测试接口
     */
    public function test(){

        //测试队列test

        $video = new Alivideo();
//        $res = $video->aliVideoUpload(6);
        $res = $video->aliVideoDownload(76);
        dump($res);die;

        $top = [11,22,33];
        $lower = [41,53,64];
        $middle = [73,84,96];
        $lower = getSortCartList($lower);
//        dump($lower);die;
        $res = getArrSet([$top,$lower,$middle]);
        //产生62个视频

        dump($res);die;
        $user = Member::where(['id'=>session('user')])->find();
        $sale = Sale::where(['id'=>3])->find();
        $res = Dy::releaseVideo($user['openid'],$user['access_token'],$sale,'');
        //item_id  @8hxdhauTCMppanGnM4ltGM780mDqPP+KPpR0qQOmLVAXb/T060zdRmYqig357zEBq6CZRp4NVe6qLIJW/V/x1w==
        dump($res['data']['item_id']);die;
        dump($user);
    }
}